import Req from '@/api/user'
import CryptoJS from 'crypto-js'
import { setToken } from '@/utils/auth'

export default {
  name: 'Login',
  data() {
    return {
      loginForm: {
        userName: '',
        password: ''
      },
      // loginRules: {
      //   userName: [
      //     {required: true, message: '请输入用户名', trigger: 'blur'},
      //     {min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur'}
      //   ],
      //   password: [
      //     {required: true, message: '请输入密码', trigger: 'blur'},
      //     {min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur'}
      //   ]
      // },
      loading: false,
      passwordVisible: false,
      rememberMe: false
    }
  },
  mounted() {
    // 检查是否有记住的密码
    const savedUsername = localStorage.getItem('username')
    const savedpassword = localStorage.getItem('password')
    if (savedUsername && savedpassword) {
      this.loginForm.userName = savedUsername
      this.loginForm.password = savedpassword
      this.rememberMe = true
    }
  },
  methods: {
    handleLogin() {
      this.$refs.loginForm.validate(async valid => {
        if (!valid) return

        this.loading = true
        try {
          this.loginForm.password = CryptoJS.MD5(this.loginForm.password).toString()

          Req.login(this.loginForm).then(res => {
            if (res.code === 200) {
              localStorage.setItem('user', JSON.stringify(res.data))

              if (this.rememberMe) {
                localStorage.setItem('username', this.loginForm.userName)
                localStorage.setItem('password', this.loginForm.password)
              } else {
                localStorage.removeItem('username')
                localStorage.removeItem('password')
              }

              // 存储 token
              setToken(CryptoJS.MD5(res.data.userName))

              this.$message.success('登录成功')

              if (res.data.roleName === '超级管理员') {
                //   管理员
                this.$router.push('/')
              } else if (res.data.roleName === '礼仪师') {
                this.$router.push('/order')
              } else {
                this.$router.push('/productManager')
              }
            }
          }).catch(e => {
            console.error(e)
            this.$message.error('登录失败，请检查用户名和密码')
          })

          // this.$router.push('/')
        } catch (error) {
          this.$message.error('登录失败，请检查用户名和密码')
        } finally {
          this.loading = false
        }
      })
    },
    handleForgetPassword() {
      this.$message.info('请联系管理员重置密码')
    }
  }
}